// DOM Elements
const appNameInput = document.getElementById('app-name');
const generateBtn = document.querySelector('.generate-btn');
const copyBtn = document.querySelector('.copy-btn');
const downloadBtn = document.querySelector('.download-btn');
const manifestContent = document.getElementById('manifest-content');
const trackingEnabled = document.getElementById('tracking-enabled');
const trackingDomains = document.querySelector('.tracking-domains');
const addDomainBtn = document.querySelector('.add-domain-btn');
const domainInput = document.getElementById('tracking-domain');
const domainList = document.querySelector('.domain-list');
const dataTypeSelect = document.getElementById('data-type-select');
const addDataTypeBtn = document.querySelector('.add-data-type-btn');
const selectedDataTypes = document.querySelector('.selected-data-types');
const dataTypeDetails = document.querySelector('.data-type-details');

// API Usage Reasons
const apiReasons = {
    'file-timestamp': {
        key: 'NSFileTimestampUsageDescription',
        name: '文件时间戳 APIs',
        description: '访问文件的时间戳信息',
        reasons: [
            {
                code: 'DDA9.1',
                en: 'Display file timestamps to the person using the device',
                zh: '向设备用户显示文件时间戳',
                note: '通过此原因访问的信息或任何衍生信息不得发送至设备外部'
            },
            {
                code: 'C617.1',
                en: 'Access timestamps, size, or other metadata of files inside the app container',
                zh: '访问应用容器内的文件时间戳和元数据',
                note: '仅限于访问应用自身的容器内文件信息'
            },
            {
                code: '3B52.1',
                en: 'Access timestamps, size, or other metadata of user granted files',
                zh: '访问用户授权的文件时间戳和元数据',
                note: '例如通过文档选择器获取的文件'
            }
        ]
    },
    'system-boot': {
        key: 'NSSystemBootTimeUsageDescription',
        name: '系统启动时间 APIs',
        description: '访问系统启动时间信息',
        reasons: [
            {
                code: '35F9.1',
                en: 'Access the system boot time to measure elapsed time between events or perform timer calculations',
                zh: '访问系统启动时间以测量事件之间的经过时间或执行计时器计算',
                note: '通过此原因访问的信息不得发送至设备外，但应用内事件之间的时间间隔信息可以发送'
            },
            {
                code: '8FFB.1',
                en: 'Calculate absolute timestamps for events within your app',
                zh: '计算应用程序内事件的绝对时间戳',
                note: '应用内事件的绝对时间戳可发送至设备外，但系统启动时间本身不得发送'
            },
            {
                code: '3D61.1',
                en: 'Include system boot time in optional bug reports',
                zh: '在可选的错误报告中包含系统启动时间信息',
                note: '仅在用户明确选择提交包含系统启动时间的错误报告后才可发送'
            }
        ]
    },
    'disk-space': {
        key: 'NSDiskSpaceUsageDescription',
        name: '磁盘空间 APIs',
        description: '访问设备存储空间信息',
        reasons: [
            {
                code: '85F4.1',
                en: 'Display disk space information to device users',
                zh: '向设备用户显示磁盘空间信息',
                note: '可以显示信息单位或媒体类型时间单位，但不得发送至设备外'
            },
            {
                code: 'E174.1',
                en: 'Check disk space for file operations and manage storage',
                zh: '检查文件操作的磁盘空间并管理存储',
                note: '用于检查写入文件的空间是否充足，或在空间不足时删除文件'
            },
            {
                code: '7D9E.1',
                en: 'Include disk space information in optional bug reports',
                zh: '在可选的错误报告中包含磁盘空间信息',
                note: '仅在用户明确选择提交包含磁盘空间信息的错误报告后才可发送'
            },
            {
                code: 'B728.1',
                en: 'Health research apps to monitor disk space for research data collection',
                zh: '健康研究应用监控研究数据收集的磁盘空间',
                note: '仅适用于符合 App Store 审核指南 §5.1.3 的健康研究应用'
            }
        ]
    },
    'keyboard': {
        key: 'NSKeyboardUsageDescription',
        name: '活动键盘 APIs',
        description: '访问键盘输入相关信息',
        reasons: [
            {
                code: '3EC4.1',
                en: 'Custom keyboard app to determine active keyboards',
                zh: '自定义键盘应用确定活动键盘',
                note: '仅适用于主要功能是提供系统级自定义键盘的应用'
            },
            {
                code: '54BD.1',
                en: 'Present customized UI based on active keyboards',
                zh: '根据活动键盘呈现自定义用户界面',
                note: '应用必须具有文本输入字段并根据活动键盘显示可观察到的不同行为'
            }
        ]
    },
    'user-defaults': {
        key: 'NSUserDefaultsUsageDescription',
        name: '用户默认设置 APIs',
        description: '访问应用的用户默认设置',
        reasons: [
            {
                code: 'CA92.1',
                en: 'Access user defaults for app-specific information',
                zh: '访问应用程序特定的用户默认信息',
                note: '仅限读写应用自身可访问的信息'
            },
            {
                code: '1C8F.1',
                en: 'Access user defaults within App Group',
                zh: '访问应用程序组内的用户默认设置',
                note: '仅限于同一 App Group 内的应用、扩展和 App Clips 之间共享信息'
            },
            {
                code: 'C56D.1',
                en: 'Third-party SDK wrapper for user defaults',
                zh: '第三方SDK的用户默认设置包装器',
                note: '仅适用于提供包装函数的第三方SDK，不得用于SDK自身目的'
            },
            {
                code: 'AC6B.1',
                en: 'Access MDM managed configuration',
                zh: '访问MDM管理的配置',
                note: '用于读取MDM设置的托管应用配置或存储MDM反馈信息'
            }
        ]
    }
};

// Data Collection Types
const dataCollectionTypes = {
    'ContactInfo': {
        groupName: '用户信息',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeName',
                typeName: '姓名',
                translationDes: '名字'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeEmailAddress',
                typeName: '电子邮件',
                translationDes: '邮箱地址'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypePhoneNumber',
                typeName: '电话号码',
                translationDes: '手机号'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypePhysicalAddress',
                typeName: '物理地址',
                translationDes: '物理地址'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeOtherUserContactInfo',
                typeName: '其他用户联系信息',
                translationDes: '其他用户联系信息'
            }
        ]
    },
    'HealthAndFitness': {
        groupName: '健康与健身',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeHealth',
                typeName: '健康数据',
                translationDes: '健康'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeFitness',
                typeName: '健身数据',
                translationDes: '健身'
            }
        ]
    },
    'FinancialInfo': {
        groupName: '财务信息',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypePaymentInfo',
                typeName: '支付信息',
                translationDes: '支付信息'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeCreditInfo',
                typeName: '信用信息',
                translationDes: '信用信息'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeOtherFinancialInfo',
                typeName: '其他财务信息',
                translationDes: '其他财务信息'
            }
        ]
    },
    'Location': {
        groupName: '位置信息',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypePreciseLocation',
                typeName: '精确位置',
                translationDes: '精确位置'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeCoarseLocation',
                typeName: '大致位置',
                translationDes: '粗略位置'
            }
        ]
    },
    'SensitiveInfo': {
        groupName: '敏感信息',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeSensitiveInfo',
                typeName: '敏感信息',
                translationDes: '敏感信息'
            }
        ]
    },
    'Contacts': {
        groupName: '通讯录',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeContacts',
                typeName: '通讯录',
                translationDes: '联系人'
            }
        ]
    },
    'UserContent': {
        groupName: '用户内容',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeEmailsOrTextMessages',
                typeName: '邮件或短信',
                translationDes: '邮件或短信'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypePhotosOrVideos',
                typeName: '照片和视频',
                translationDes: '照片或视频'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeAudioData',
                typeName: '音频数据',
                translationDes: '音频数据'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeGameplayContent',
                typeName: '游戏内容',
                translationDes: '游戏内容'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeCustomerSupport',
                typeName: '客户支持',
                translationDes: '客户支持'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeOtherUserContent',
                typeName: '其他用户内容',
                translationDes: '其他用户内容'
            }
        ]
    },
    'BrowsingHistory': {
        groupName: '浏览历史',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeBrowsingHistory',
                typeName: '浏览历史',
                translationDes: '浏览历史'
            }
        ]
    },
    'SearchHistory': {
        groupName: '搜索历史',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeSearchHistory',
                typeName: '搜索历史',
                translationDes: '搜索历史'
            }
        ]
    },
    'Identifiers': {
        groupName: '标识符',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeUserID',
                typeName: '用户ID',
                translationDes: '用户ID'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeDeviceID',
                typeName: '设备ID',
                translationDes: '设备ID'
            }
        ]
    },
    'Purchase': {
        groupName: '购买记录',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypePurchaseHistory',
                typeName: '购买历史',
                translationDes: '购买历史'
            }
        ]
    },
    'UsageData': {
        groupName: '使用数据',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeProductInteraction',
                typeName: '产品交互',
                translationDes: '产品交互'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeAdvertisingData',
                typeName: '广告数据',
                translationDes: '广告数据'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeOtherUsageData',
                typeName: '其他使用数据',
                translationDes: '其他使用数据'
            }
        ]
    },
    'Diagnostics': {
        groupName: '诊断数据',
        items: [
            {
                typeKey: 'NSPrivacyCollectedDataTypeCrashData',
                typeName: '崩溃数据',
                translationDes: '崩溃数据'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypePerformanceData',
                typeName: '性能数据',
                translationDes: '性能数据'
            },
            {
                typeKey: 'NSPrivacyCollectedDataTypeOtherDiagnosticData',
                typeName: '其他诊断数据',
                translationDes: '其他诊断数据'
            }
        ]
    }
};

// Target Items
const targetItems = [
    {
        typeKey: 'NSPrivacyCollectedDataTypeLinked',
        explain: 'Linked to identity',
        translationDes: '与身份关联'
    },
    {
        typeKey: 'NSPrivacyCollectedDataTypeTracking',
        explain: 'Collected for tracking',
        translationDes: '收集用于跟踪'
    }
];

// Tracking Reasons
const trackingReasons = [
    {
        typeKey: 'NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising',
        explain: '3rd party ads',
        translationDes: '三方广告'
    },
    {
        typeKey: 'NSPrivacyCollectedDataTypePurposeDeveloperAdvertising',
        explain: 'Developer ads',
        translationDes: '开发者广告'
    },
    {
        typeKey: 'NSPrivacyCollectedDataTypePurposeAnalytics',
        explain: 'Analytics',
        translationDes: '分析'
    },
    {
        typeKey: 'NSPrivacyCollectedDataTypePurposeProductPersonalization',
        explain: 'Personalization',
        translationDes: '个性化'
    },
    {
        typeKey: 'NSPrivacyCollectedDataTypePurposeAppFunctionality',
        explain: 'App Functionality',
        translationDes: '应用程序功能'
    },
    {
        typeKey: 'NSPrivacyCollectedDataTypePurposeOther',
        explain: 'Others',
        translationDes: '其他'
    }
];

// Event Listeners
trackingEnabled.addEventListener('change', () => {
    trackingDomains.style.display = trackingEnabled.checked ? 'block' : 'none';
});

addDomainBtn.addEventListener('click', addDomain);
generateBtn.addEventListener('click', generateManifest);
copyBtn.addEventListener('click', copyToClipboard);
downloadBtn.addEventListener('click', downloadManifest);

// 添加API类别选择事件监听
document.querySelectorAll('.api-option input[type="checkbox"]').forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        const apiId = this.id;
        const reasonsContainer = document.querySelector(`.api-reasons[data-for="${apiId}"]`);
        if (reasonsContainer) {
            if (this.checked) {
                // 获取API类别的原因列表
                const api = apiReasons[apiId];
                if (api && api.reasons) {
                    // 清空现有的原因选项
                    const reasonOptionsContainer = reasonsContainer.querySelector('.reason-options');
                    reasonOptionsContainer.innerHTML = '';
                    
                    // 添加每个原因选项
                    api.reasons.forEach(reason => {
                        const reasonOption = document.createElement('div');
                        reasonOption.className = 'reason-option';
                        reasonOption.innerHTML = `
                            <input type="checkbox" id="${reason.code}-${apiId}" name="api-reason">
                            <label for="${reason.code}-${apiId}">
                                <code>${reason.code}</code>
                                <span class="reason-text">
                                    <span class="zh">${reason.zh}</span>
                                    <span class="en">${reason.en}</span>
                                </span>
                                <div class="reason-note">${reason.note}</div>
                            </label>
                        `;
                        reasonOptionsContainer.appendChild(reasonOption);
                    });
                }
                
                reasonsContainer.style.display = 'block';
                // 使用 setTimeout 来确保过渡动画生效
                setTimeout(() => {
                    reasonsContainer.classList.add('show');
                }, 10);
            } else {
                reasonsContainer.classList.remove('show');
                // 等待过渡动画完成后隐藏
                setTimeout(() => {
                    reasonsContainer.style.display = 'none';
                }, 300);
                // 取消选中所有原因
                reasonsContainer.querySelectorAll('input[type="checkbox"]').forEach(cb => {
                    cb.checked = false;
                });
            }
        }
    });
});

// 添加数据收集类型的事件监听
document.querySelectorAll('.data-option input[type="checkbox"]').forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        const dataId = this.id;
        const targetContainer = document.querySelector(`.data-targets[data-for="${dataId}"]`);
        const reasonsContainer = document.querySelector(`.data-reasons[data-for="${dataId}"]`);
        
        if (targetContainer && reasonsContainer) {
            if (this.checked) {
                // 显示目标选项
                targetContainer.innerHTML = `
                    <div class="target-options">
                        ${targetItems.map(target => `
                            <div class="target-option">
                                <input type="checkbox" id="${target.typeKey}-${dataId}" name="data-target">
                                <label for="${target.typeKey}-${dataId}">
                                    <span class="zh">${target.translationDes}</span>
                                    <span class="en">${target.explain}</span>
                                </label>
                            </div>
                        `).join('')}
                    </div>
                `;
                
                // 显示原因选项
                reasonsContainer.innerHTML = `
                    <div class="reason-options">
                        ${trackingReasons.map(reason => `
                            <div class="reason-option">
                                <input type="checkbox" id="${reason.typeKey}-${dataId}" name="data-reason">
                                <label for="${reason.typeKey}-${dataId}">
                                    <span class="zh">${reason.translationDes}</span>
                                    <span class="en">${reason.explain}</span>
                                </label>
                            </div>
                        `).join('')}
                    </div>
                `;
                
                targetContainer.style.display = 'block';
                reasonsContainer.style.display = 'block';
                
                setTimeout(() => {
                    targetContainer.classList.add('show');
                    reasonsContainer.classList.add('show');
                }, 10);
            } else {
                targetContainer.classList.remove('show');
                reasonsContainer.classList.remove('show');
                
                setTimeout(() => {
                    targetContainer.style.display = 'none';
                    reasonsContainer.style.display = 'none';
                }, 300);
                
                // 取消选中所有选项
                targetContainer.querySelectorAll('input[type="checkbox"]').forEach(cb => {
                    cb.checked = false;
                });
                reasonsContainer.querySelectorAll('input[type="checkbox"]').forEach(cb => {
                    cb.checked = false;
                });
            }
        }
    });
});

// 初始化选中的数据类型集合
const selectedTypes = new Set();

// 添加数据类型选择事件监听
addDataTypeBtn.addEventListener('click', () => {
    const selectedOption = dataTypeSelect.options[dataTypeSelect.selectedIndex];
    const typeKey = selectedOption.value;
    const typeName = selectedOption.text;
    const groupName = selectedOption.parentElement.label;
    
    if (!typeKey) {
        alert('请选择一个数据类型');
        return;
    }
    
    if (selectedTypes.has(typeKey)) {
        alert('该数据类型已经添加');
        return;
    }
    
    // 添加数据类型卡片
    addDataTypeCard(typeKey, typeName, groupName);
    selectedTypes.add(typeKey);
    
    // 更新已添加项显示
    updateSelectedItemsDisplay();
    
    // 重置选择
    dataTypeSelect.value = '';
});

// 添加数据类型卡片
function addDataTypeCard(typeKey, typeName, groupName) {
    // 检查是否已存在
    if (selectedTypes.has(typeKey)) {
        alert('该数据类型已经添加');
        return;
    }

    // 获取已选择的数据使用目标
    const selectedTargets = Array.from(document.querySelectorAll('.data-targets-section .target-option input:checked'))
        .map(input => {
            const targetLabel = input.closest('.target-option').querySelector('span').textContent;
            return {
                key: input.value,
                label: targetLabel
            };
        });

    // 获取已选择的收集目的
    const selectedPurposes = Array.from(document.querySelectorAll('.data-purposes-section .purpose-option input:checked'))
        .map(input => {
            const purposeLabel = input.closest('.purpose-option').querySelector('span').textContent;
            return {
                key: input.value,
                label: purposeLabel
            };
        });

    if (selectedPurposes.length === 0) {
        alert('请至少选择一个收集目的');
        return;
    }

    // 添加到已选择的数据类型集合
    selectedTypes.add(typeKey);

    // 获取已选择项的容器
    const itemsGrid = document.querySelector('.selected-items-grid');
    if (!itemsGrid) return;

    // 创建数据类型子卡片
    const itemCard = document.createElement('div');
    itemCard.className = 'selected-item';
    itemCard.dataset.typeKey = typeKey;
    
    itemCard.innerHTML = `
        <div class="item-header">
            <div class="item-info">
                <span class="item-group">${groupName}</span>
                <span class="item-name">${typeName}</span>
            </div>
            <button class="remove-item-btn" onclick="removeSelectedItem('${typeKey}')">移除</button>
        </div>
        <div class="item-summary">
            <div class="item-targets-summary">
                <span class="summary-label">数据使用目标：</span>
                <div class="selected-targets">
                    ${selectedTargets.length > 0 ? 
                        selectedTargets.map(target => `
                            <span class="target-tag">
                                <input type="hidden" name="${target.key}" value="${target.key}">
                                ${target.label}
                            </span>
                        `).join('') : 
                        '<span class="no-selection">未选择使用目标</span>'
                    }
                </div>
            </div>
            <div class="item-purposes-summary">
                <span class="summary-label">收集目的：</span>
                <div class="selected-purposes">
                    ${selectedPurposes.map(purpose => `
                        <span class="purpose-tag">
                            <input type="hidden" name="${purpose.key}" value="${purpose.key}">
                            ${purpose.label}
                        </span>
                    `).join('')}
                </div>
            </div>
        </div>
    `;

    // 添加到容器中
    itemsGrid.appendChild(itemCard);
    
    // 添加动画效果
    requestAnimationFrame(() => {
        itemCard.classList.add('show');
    });

    // 重置选择器
    dataTypeSelect.value = '';

    // 更新预览
    updateManifestPreview();
}

// 移除数据类型子卡片
function removeSelectedItem(typeKey) {
    const itemCard = document.querySelector(`.selected-item[data-type-key="${typeKey}"]`);
    if (!itemCard) return;

    // 添加移除动画
    itemCard.classList.remove('show');
    
    // 等待动画完成后移除元素
    setTimeout(() => {
        itemCard.remove();
        selectedTypes.delete(typeKey);
        updateManifestPreview();
    }, 300);
}

// 更新数据类型子卡片的选择状态
function updateItemSummary(typeKey) {
    const itemCard = document.querySelector(`.selected-item[data-type-key="${typeKey}"]`);
    if (!itemCard) return;

    // 更新预览
    updateManifestPreview();
}

// 更新清单预览
function updateManifestPreview() {
    const selectedData = [];
    document.querySelectorAll('.selected-item').forEach(card => {
        const typeKey = card.dataset.typeKey;
        const typeName = card.querySelector('.item-name').textContent;
        const groupName = card.querySelector('.item-group').textContent;
        
        // 获取选中的目标
        const targets = Array.from(card.querySelectorAll('.target-options input:checked'))
            .map(input => {
                const label = input.closest('label');
                return {
                    key: input.value,
                    zh: label.querySelector('.zh').textContent
                };
            });
            
        // 获取选中的目的
        const purposes = Array.from(card.querySelectorAll('.purpose-options input:checked'))
            .map(input => {
                const label = input.closest('label');
                return {
                    key: input.value,
                    zh: label.querySelector('.zh').textContent
                };
            });
        
        selectedData.push({
            typeKey,
            typeName,
            groupName,
            targets,
            purposes
        });
    });

    // 更新预览内容
    const previewContent = generateDataTypePreview(selectedData);
    manifestContent.textContent = previewContent;
}

// Functions
function addDomain() {
    const domain = domainInput.value.trim();
    if (!domain) return;
    
    if (!isValidDomain(domain)) {
        alert('请输入有效的域名');
        return;
    }
    
    const li = document.createElement('li');
    li.innerHTML = `
        ${domain}
        <button onclick="this.parentElement.remove()" class="remove-domain">删除</button>
    `;
    domainList.appendChild(li);
    domainInput.value = '';
}

function isValidDomain(domain) {
    const pattern = /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
    return pattern.test(domain);
}

function generateManifest() {
    const appName = appNameInput.value.trim();
    if (!appName) {
        alert('请输入应用名称');
        return;
    }

    // 收集选中的API类别和原因
    const selectedAPIs = Array.from(document.querySelectorAll('.api-option input:checked')).map(input => {
        const apiId = input.id;
        const reasons = Array.from(
            document.querySelectorAll(`.api-reasons[data-for="${apiId}"] input:checked`)
        ).map(reasonInput => {
            // 只获取原因代码，不包含后缀
            const reasonCode = reasonInput.id.split('-')[0];
            return reasonCode;
        });
        
        return {
            id: apiId,
            key: apiReasons[apiId].key,
            reasons: reasons
        };
    });

    // 收集选中的数据类型、使用目标和收集目的
    const selectedDataTypes = Array.from(document.querySelectorAll('.selected-item')).map(item => {
        const typeKey = item.dataset.typeKey;
        
        // 获取数据使用目标
        const targets = Array.from(item.querySelectorAll('.target-tag input[type="hidden"]'))
            .map(input => input.value);
        
        // 获取收集目的
        const purposes = Array.from(item.querySelectorAll('.purpose-tag input[type="hidden"]'))
            .map(input => input.value);
        
        return {
            typeKey,
            targets,
            purposes
        };
    });

    // 生成 plist 内容
    let content = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>NSPrivacyAccessedAPITypes</key>
    <array>`;

    // 添加 API 类别
    selectedAPIs.forEach(api => {
        if (api.reasons.length > 0) {
            content += `
        <dict>
            <key>NSPrivacyAccessedAPIType</key>
            <string>${api.key}</string>
            <key>NSPrivacyAccessedAPITypeReasons</key>
            <array>`;
            
            api.reasons.forEach(reason => {
                content += `
                <string>${reason}</string>`;
            });

            content += `
            </array>
        </dict>`;
        }
    });

    content += `
    </array>

    <key>NSPrivacyCollectedDataTypes</key>
    <array>`;

    // 添加数据收集类型
    selectedDataTypes.forEach(dataType => {
        content += `
        <dict>
            <key>NSPrivacyCollectedDataType</key>
            <string>${dataType.typeKey}</string>`;

        // 添加数据使用目标
        dataType.targets.forEach(target => {
            content += `
            <key>${target}</key>
            <true/>`;
        });

        // 添加收集目的
        if (dataType.purposes.length > 0) {
            content += `
            <key>NSPrivacyCollectedDataTypePurposes</key>
            <array>`;
            
            dataType.purposes.forEach(purpose => {
                content += `
                <string>${purpose}</string>`;
            });

            content += `
            </array>`;
        }

        content += `
        </dict>`;
    });

    content += `
    </array>
</dict>
</plist>`;

    // 更新预览内容
    const manifestOutput = document.querySelector('.manifest-output pre');
    if (manifestOutput) {
        manifestOutput.textContent = content;
    }
}

function copyToClipboard() {
    const text = manifestContent.textContent;
    navigator.clipboard.writeText(text)
        .then(() => {
            const originalText = copyBtn.textContent;
            copyBtn.textContent = '已复制！';
            setTimeout(() => {
                copyBtn.textContent = originalText;
            }, 2000);
        })
        .catch(err => {
            console.error('复制失败:', err);
            alert('复制失败，请手动复制');
        });
}

function downloadManifest() {
    const content = manifestContent.textContent;
    const blob = new Blob([content], { type: 'text/xml' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'PrivacyInfo.xcprivacy';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}